#include <func.h>

int main(void)
{
    char *ip = "192.168.12.129";
    char *post = "8080";

    struct sockaddr_in SockAdd;
    SockAdd.sin_family = AF_INET;
    SockAdd.sin_port = htons(atoi(post));
    SockAdd.sin_addr.s_addr = inet_addr(ip);

    int SockFd = socket(AF_INET,SOCK_STREAM,0);
    
    int con = connect(SockFd,(struct sockaddr *)&SockAdd,sizeof(SockAdd));    
    if(con == -1)
        error(1,errno,"connect erro!\n");

    int EpollFd = epoll_create(1);

    struct epoll_event Event;
    Event.events = EPOLLIN;
    Event.data.fd = STDIN_FILENO;
    epoll_ctl(EpollFd,EPOLL_CTL_ADD,STDIN_FILENO,&Event);

    Event.data.fd = SockFd;
    epoll_ctl(EpollFd,EPOLL_CTL_ADD,SockFd,&Event);

    while(true)
    {
        struct epoll_event Events[5];

        int num = epoll_wait(EpollFd,Events,5,0);
        
        for(int i = 0;i < num;i++)
        {
            int temp = Events[i].data.fd;
            char buf[60] = {0};
            if(temp == STDIN_FILENO)
            {
                read(STDIN_FILENO,buf,sizeof(buf) - 1);
                buf[strlen(buf) - 1] = '\0';
                send(SockFd,buf,sizeof(buf),0);
            }
            if(temp == SockFd)
            {
                char buff[60] = {0};
                int ret = recv(SockFd,buff,sizeof(buff),0);
                
                if(ret == 0)
                {
                    printf("服务器断开连接！\n");
                    goto end;
                }
                
                int FileFd = open("A.txt",O_RDWR | O_CREAT | O_APPEND,0666);
                if(FileFd == -1)
                    printf("Erro:open %s",buf);
                else
                {
                    printf("收到服务器数据： %s \n",buff);
                
                    write(FileFd,buff,strlen(buff));
                    close(FileFd);
                }
            }
        }
    }
end:
    close(SockFd);
    return 0;
}

